﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KongZhiTaiTest
{

    /// <summary>
    /// 所有有关流测试的集合
    /// </summary>
    public class StreamCellection
    {
        
        public static void Show(StreamType type)
        {
            switch (type)
            {
                case StreamType.Stream:
                    break;
                case StreamType.MemoryStream:
                    MemoryStreamTest.TestStream();
                    break;
                default:
                    break;
            }

        }
        
    }

    /// <summary>
    /// stream 流的测试
    /// 1.本质就是以字节数组存储的
    /// 2.可以理解成冲字节数组缓冲区与memorystream 之间进行数据拷贝
    /// 3.注意使用using块
    /// 4.注意steam.Position 需要正确理解，相当于stream本身的一个指针。
    /// </summary>
    public class MemoryStreamTest
    {
        public static void TestStream()
        {
            //准备一些数据
            string testString = "stream!Hollow world";
            byte[] buffer = null;
            byte[] readBuffer = null;
            string readString = string.Empty;
            using(MemoryStream stream = new MemoryStream())
            {
                //判断流是否可写
                if (stream.CanWrite)
                {
                    //将testString 写入流中，首先将string -> byte[]
                    buffer = Encoding.Default.GetBytes(testString);
                    stream.Write(buffer, 0, 3);
                    //上边写了3个字节了，然后重新定位一下啊流当前的位置
                    Console.WriteLine($"stream 当前的位置{stream.Position +1}"); 
                    long newSteamPoint = stream.CanSeek ? stream.Seek(3, SeekOrigin.Current) :0;
                    Console.WriteLine($"stream 重置后的位置{stream.Position+1}");
                    //可以看一下源代码会有很多收获的。
                    if(newSteamPoint < buffer.Length)
                        stream.Write(buffer, (int)newSteamPoint, buffer.Length - (int)newSteamPoint);
                    //接下来将stream 中的数据读出来
                    //1.准备一个容器接受数据
                    readBuffer = new byte[stream.Length];
                    //2.设置一下stream的位置
                    stream.Position = 0;
                    //3.开始 读取数据
                    Console.WriteLine($"流中一共有{(int)stream.Length}个字节");
                    int num =stream.CanRead? stream.Read(readBuffer, 8,(int)stream.Length -8):0;

                    //因为一开始我们将数据Encoding加密，必须解密成char数组才能转换成string 
                    char[] charString = Encoding.Default.GetChars(readBuffer);
                    charString.ToList().ForEach(item => readString += item);
                    Console.WriteLine($"最终得到的数据是：{readString}");
                }
                stream.Close();
            }

        }
    }

    public class FileStreamTest
    {
        

    }
    
    /// <summary>
    /// 流的类型
    /// </summary>
    public enum StreamType
    {
        Stream = 1,
        MemoryStream =2,
        
    }
}
